<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/6/8
 * Time: 9:55
 */

namespace app\api\controller\v1\balance;

use think\facade\Db;
use app\middleware\BackAuth;
use think\Request;
use think\facade\Validate;
use think\response\Json;
use think\validate\ValidateRule;
use app\api\model\GoodsModel;
use \Exception;

/*
 * 采购员 管理控制器
 * */

class Buyer
{
// 权限校验
    protected $middleware = [BackAuth::class];

    /**获取三级分类 以及分类下的所有商品 单位 库存
     * @param Request $request
     * @return Json
     */
    public function getProductList(Request $request)
    {
        try {
            $center_id = $request->post('center_id'); // 分拣中心id
            // 参数校验
            if ($center_id == null) return jsonFail('缺少参数');
            $field = 'sp.ice_stock,sp.status,sp.cate_id,sc.name as cate_name,sp.id as product_id,sp.stock, sp.name as goods_name,sp.image,sp.info,sp.sales,
            c.name as unit_name,c.type';
            $data = Db::table('goods')->alias('sp')
                ->join(['category' => 'sc'], 'sp.cate_id = sc.id')
                ->join('goods_unit c ', 'sp.unit_id= c.id')
                ->field($field)
//                ->where('sp.status', 1)
                ->where('sp.center_id', $center_id)
                ->select()
                ->toArray();
            if (!$data) return jsonSuccess('暂无数据', []);
            $outData = [];

            foreach ($data as $v) {
                // 三级分类信息
                $cateInfo['cate_id'] = $v['cate_id'];
                $cateInfo['cate_name'] = $v['cate_name'];
                // 商品信息
                $productInfo['status'] = $v['status'];
                $productInfo['ice_stock'] = $v['ice_stock'];
                $productInfo['product_id'] = $v['product_id'];
                $productInfo['goods_name'] = $v['goods_name'];
                $productInfo['unit_name'] = $v['unit_name'];
                $productInfo['image'] = $v['image'];
                $productInfo['stock'] = $v['stock'];
                $productInfo['info'] = $v['info'];
                $productInfo['sales'] = $v['sales'];
                $productInfo['type'] = $v['type'];
//                // 规格信息
//                $attr['stock'] = $v['stock'];
//                $attr['suk'] = $v['suk'];
//                $attr['unique'] = $v['unique'];
//                $attr['specif'] = $v['specif'];
                if (!$cateInfo['cate_id']) {
                    continue;
                }
                if (!key_exists($cateInfo['cate_id'], $outData)) {
                    $cateInfo['products'] = [];
                    $outData[$v['cate_id']] = $cateInfo;
                }
                if (!$productInfo['product_id']) {
                    continue;
                }
                if (!key_exists($productInfo['product_id'], $outData[$v['cate_id']]['products'])) {
//                    $productInfo['attr'] = [];
                    $outData[$v['cate_id']]['products'][$productInfo['product_id']] = $productInfo;
                }
            }

            return jsonSuccess('获取成功', array_values($outData));
        } catch (Exception $e) {
            return jsonFail('服务内部错误~', [$e->getMessage()]);
        }
    }

    /** 查看商品日志
     * @param Request $request
     * @return Json
     */
    public function goodsLog(Request $request)
    {
        // 判断参数是否合法
        $input['type'] = $request->param('type');//1:入库  2：出库 3：报损  4:采购
        $input['goods_id'] = $request->param('goods_id');//商品ID
        // 参数校验
        $validate = Validate::rule([
            'type' => ValidateRule::isRequire(),
            'goods_id' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        return GoodsModel::goodsLogs($input);
    }

    /** 模糊获取商品名字、单位
     * @param Request $request
     * @return Json
     */
    public function getAttrList(Request $request)
    {
        $center_id = $request->post('center_id'); // 分拣中心id
        $name = $request->post('name', ''); // 商品名字
        // 参数校验
        if ($center_id == null) return jsonFail('缺少参数');
        if ($name == null) return jsonFail('缺少参数');
        $data = Db::table('goods')->alias('a')->join('goods_unit b', 'a.unit_id = b.id')->where('a.center_id', $center_id)->whereLike('a.name', '%' . $name . '%')->field('a.id,a.name,b.name as unit_name,b.type')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /** 添加该商品采购记录
     * @param Request $request
     * @return Json
     */
    public function warehouse(Request $request)
    {
        $affair = false; // 关闭事务
        try {
            $productId = $request->post('goods_id'); // 商品id
            $p_weight = $request->post('p_weight');// 采购重量
            $price = $request->post('price');// 成本价
            $center_id = $request->post('center_id');// 分拣中心ID
            $type = $request->post('type');// 1:过称 2：不过秤
            $Warehousing_id = $request->param('Warehousing_id');//采购人ID
            // 参数校验
            if ($productId == null) return jsonFail('缺少参数');
            if ($p_weight == null) return jsonFail('缺少参数');
            if (empty($price) || empty($center_id) || empty($Warehousing_id) || empty($type)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $Warehousing_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('操作人信息有误');

            // 更新属性 以及商品信息
            Db::startTrans();
            $affair = true; // 开启事务
            $productRtn = Db::table('purchase')
                ->insertGetId([
                    'uid' => $Warehousing_id,
                    'goods_id' => $productId,
                    'center_id' => $center_id,
                    'price' => $price,
                    'p_weight' => $p_weight,
                    'type' => $type,
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
            if ($productRtn != 0) {
                Db::commit();
                return jsonSuccess('登记成功');
            }
            Db::rollback();
            return jsonFail('登记失败');
        } catch (Exception $e) {
            if ($affair == true) {
                Db::rollback();
            }
            return jsonFail('服务内部错误~');
        }
    }

    /** 库管员复核入库
     * @param Request $request
     * @return Json
     */
    public function RecheckWare(Request $request)
    {
        try {
            $Warehousing_id = $request->param('Warehousing_id');//库管员ID
            $purchase_id = $request->param('purchase_id');//采购记录ID
            $weight = $request->param('weight');//复核入库数量
            $admin_id = $request->param('admin_id');//运营商ID
            $reason = $request->param('reason', '');//原因
            if (empty($Warehousing_id) || empty($weight) || empty($purchase_id) || empty($admin_id)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $Warehousing_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('操作人信息有误');
            //更新采购记录
            $purchase_data = Db::table('goods')->alias('g')
                ->join(['purchase' => 'p'], 'p.goods_id = g.id')
                ->field('goods_id,ot_price_percent,price_percent,p.price')
                ->where('p.id', $purchase_id)->find();
            if (empty($purchase_data)) return jsonFail('信息有误');
//            if ($purchase_data['type'] != 2) return jsonFail('该商品必须过称才能复核入库');
            // 更新商品信息
            Db::startTrans();
            $res = Db::table('goods')
                ->where('id', $purchase_data['goods_id'])
                ->update([
                    'stock' => Db::raw("`stock` + {$weight}"),
                    'ot_price' => round($purchase_data['price'] * $purchase_data['ot_price_percent'] / 100, 2),
                    'price' => round($purchase_data['price'] * $purchase_data['price_percent'] / 100, 2),
                    'pur_price' => $purchase_data['price']
                ]);
            //记录日志
            $red = Db::table('goods_log')->insertGetId([
                'type' => 1,
                'uid' => $Warehousing_id,
                'goods_id' => $purchase_data['goods_id'],
                'equipment' => '无需称重，复核入库，暂无设备号',
                'order_id' => $purchase_id,
                'weight' => $weight,
                'admin_id' => $admin_id,
                'name' => $role['name'],
                'phone' => $role['phone'],
                'role_type' => $role['role_type'],
                'create_time' => time(),
            ]);
            //更新采购记录
            $rea = Db::table('purchase')->where('id', $purchase_id)->update([
                'w_weight' => $weight,
                'status' => 2,
                'reason' => $reason,
            ]);
            if ($res != 0 && $red && $rea != 0) {
                Db::commit();
                return jsonSuccess('复核入库成功');
            } else {
                Db::rollback();
                return jsonFail('复核入库失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /** 获取该分拣中心下所有退货订单
     * @param Request $request
     * @return Json
     */
    public function getReturnOrder(Request $request)
    {
        try {
            $id = $request->post('id'); // 分拣中心id
            // 参数校验
            if ($id == null) return jsonFail('缺少参数');
            // 获取退货订单
            $data = Db::table('order')->field('id,order_id,store_name')->where('sort_center_id', $id)->where('status', -3)->select()->toArray();
            if ($data) return jsonSuccess('获取成功', $data);
            return jsonFail('未找到退货订单');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 通过主订单id获取退货订单的商品信息
     * @param Request $request
     * @return Json
     */
    public function getReturnOrderById(Request $request)
    {
        try {
            $id = $request->post('id'); // 主订单id
            // 参数校验
            if ($id == null) return jsonFail('缺少参数');
            // 获取退货订单
            $data = Db::table('order')->alias('sod')
                ->join(['goods' => 'sp'], 'sod.product_id = sp.id')
                ->field('sp.*')->where('sod.pid', $id)->where('sod.status', -3)->select()->toArray();
            if ($data) return jsonSuccess('获取成功', $data);
            return jsonFail('未找到退货订单');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取下单统计列表
     * @param Request $request
     * @return Json
     */
    public function getStatisticsList(Request $request)
    {
        // 获取参数
        $input['start'] = $request->post('start');
        $input['end'] = $request->post('end');
        $input['admin_id'] = $request->post('admin_id');
        // 参数校验
        $validate = Validate::rule([
            'admin_id' => ValidateRule::isRequire(null, '缺少参数'),
            'start' => function ($value) {
                return checkDatetime($value, true) ? true : '不合法参数';
            },
            'end' => function ($value) {
                return checkDatetime($value, true) ? true : '不合法参数';
            }
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        try {
            $field = 'c.name as company_name,o.goods_data,sum(o.num) as goods_num,o.group_id,g.stock,g.status as goods_status';
            $map[] = [
                ['o.admin_id', '=', $input['admin_id']],
                ['o.status', '=', 0],
                ['o.is_pay', '=', 1],
                ['o.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]]
            ];
            $table = Db::table('company')->alias('c')
                ->Join(['order' => 'o'], 'c.id = o.group_id')
                ->join(['goods' => 'g'], 'g.id = o.goods_id')
                ->where($map)->group(['o.goods_id', 'o.group_id']);
            $table->removeOption('field');
            $list = $table->field($field)->order('o.goods_id')->select()->toArray();
            // 数据整合
            $data = [];
            $total = [];
            foreach ($list as $v) {
                $goodsData = json_decode($v['goods_data'], true);
                $data[] = [
                    'company_name' => $v['company_name'],
                    'goods_name' => $goodsData['name'],
                    'goods_num' => $v['goods_num'],
                    'goods_unit' => $goodsData['unit_name']
                ];
                if (isset($total[$goodsData['name']])) {
                    $total[$goodsData['name']]['goods_num'] += $v['goods_num'];
                } else {
                    $total[$goodsData['name']] = [
                        'goods_name' => $goodsData['name'],
                        'goods_num' => $v['goods_num'],
                        'goods_unit' => $goodsData['unit_name'],
                        'goods_stock' => $v['stock'],
                        'goods_status' => $v['goods_status'],
                    ];
                }
            }
            return jsonSuccess('获取成功', ['list' => $data,'total' => $total]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}